<template>
  <div class="image-container">
    <div class="main-content">
      <div class="selection-panel">
        <h2>图片资源生成配置</h2>
        
        <!-- 教学阶段选择 -->
        <div class="form-item">
          <label>教学阶段</label>
          <el-select v-model="formData.stage" placeholder="请选择教学阶段" @change="handleStageChange">
            <el-option
              v-for="item in stages"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <!-- 教学科目选择 -->
        <div class="form-item">
          <label>教学科目</label>
          <el-select v-model="formData.subject" placeholder="请选择教学科目" @change="handleSubjectChange">
            <el-option
              v-for="item in subjects"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <!-- 教学目标选择 -->
        <div class="form-item">
          <label>教学目标</label>
          <el-input
            v-model="formData.objective"
            type="textarea"
            :rows="3"
            placeholder="请输入教学目标，例如：帮助学生理解三角函数的基本概念，培养解决几何问题的能力"
          />
        </div>

        <!-- 图片数量选择 -->
        <div class="form-item">
          <label>图片数量</label>
          <el-input-number v-model="formData.imageCount" :min="1" :max="10" />
        </div>

        <!-- 图片风格选择 -->
        <div class="form-item">
          <label>图片风格</label>
          <el-input
            v-model="formData.style"
            placeholder="请输入图片风格，例如：卡通风格、写实风格、插画风格、水彩画风格等"
          />
        </div>

        <!-- 图片尺寸选择 -->
        <div class="form-item">
          <label>图片尺寸</label>
          <el-select v-model="formData.size" placeholder="请选择图片尺寸">
            <el-option label="小尺寸 (800x600)" value="small" />
            <el-option label="中尺寸 (1200x800)" value="medium" />
            <el-option label="大尺寸 (1920x1080)" value="large" />
          </el-select>
        </div>
      </div>

      <div class="action-panel">
        <el-button type="primary" @click="generateImages" :loading="isGenerating">
          <el-icon><Picture /></el-icon>
          生成图片
        </el-button>
      </div>

      <div v-if="imageList.length > 0" class="image-list">
        <h2>生成的图片</h2>
        <div class="image-grid">
          <div v-for="(image, index) in imageList" :key="index" class="image-item">
            <div class="image-wrapper">
              <el-image 
                :src="image.url" 
                fit="cover" 
                :load-failed="image.loadFailed"
                @error="handleImageError(image)"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><i class="el-icon-picture"></i></el-icon>
                    <p>图片加载失败</p>
                    <el-button size="small" @click="reloadImage(image)">重试</el-button>
                  </div>
                </template>
              </el-image>
              <div class="image-actions">
                <el-button 
                  type="primary" 
                  circle 
                  @click="handlePreview(image)"
                  :icon="ZoomIn"
                />
                <el-button 
                  type="success" 
                  circle 
                  @click="handleDownload(image)"
                  :icon="Download"
                />
              </div>
            </div>
            <div class="image-info">
              <h3>{{ image.title || '教学图片' }}</h3>
              <p>{{ image.description || '暂无描述' }}</p>
              <div class="image-meta">
                <span>尺寸：{{ image.size || '未知' }}</span>
                <span>格式：{{ image.format || 'jpg' }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="图片预览"
      width="80%"
      :close-on-click-modal="false"
      class="image-preview-dialog"
    >
      <div class="preview-content">
        <el-image 
          :src="previewUrl" 
          fit="contain"
          :preview-src-list="[previewUrl]"
          @error="handlePreviewError"
        >
          <template #error>
            <div class="preview-error">
              <el-icon><i class="el-icon-picture"></i></el-icon>
              <p>图片预览加载失败</p>
              <el-button @click="reloadPreview">重试</el-button>
            </div>
          </template>
        </el-image>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { 
  fetchImageHistory, 
  downloadImage, 
  previewImage,
  generateTeachingImage
} from '@/api/ImageAI'
import { Download, ZoomIn, Picture } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 表单数据
const formData = ref({
  stage: '',
  subject: '',
  objective: '',
  imageCount: 1,
  style: '',
  size: ''
})

// 选项数据
const stages = ref([
  { value: 'primary', label: '小学' },
  { value: 'junior', label: '初中' },
  { value: 'senior', label: '高中' },
  { value: 'university', label: '大学' }
])

// 模拟科目数据
const subjectsMap = {
  primary: [
    { value: 'math', label: '数学' },
    { value: 'chinese', label: '语文' },
    { value: 'english', label: '英语' }
  ],
  junior: [
    { value: 'math', label: '数学' },
    { value: 'chinese', label: '语文' },
    { value: 'english', label: '英语' },
    { value: 'physics', label: '物理' },
    { value: 'chemistry', label: '化学' }
  ],
  senior: [
    { value: 'math', label: '数学' },
    { value: 'chinese', label: '语文' },
    { value: 'english', label: '英语' },
    { value: 'physics', label: '物理' },
    { value: 'chemistry', label: '化学' },
    { value: 'biology', label: '生物' }
  ],
  university: [
    { value: 'math', label: '高等数学' },
    { value: 'physics', label: '大学物理' },
    { value: 'chemistry', label: '大学化学' }
  ]
}

const subjects = ref([])

// 图片相关
const imageList = ref([])

// 图片预览相关
const previewVisible = ref(false)
const previewUrl = ref('')
const previewTitle = ref('')

// 图片生成状态
const isGenerating = ref(false)

// 加载历史记录
const loadHistoryList = () => {
  // 使用模拟数据，跳过API调用
  // historyList.value = await fetchImageHistory()
}

// 选择历史记录
const selectHistory = (index) => {
  // selectedHistory.value = index
  // const history = historyList.value[index]
  // if (history) {
  //   // 更新表单数据
  //   formData.value = {
  //     stage: history.stage,
  //     subject: history.subject,
  //     objective: history.objectives || '',
  //     imageCount: history.imageCount,
  //     style: history.style,
  //     size: history.size
  //   }
  //   
  //   // 更新图片列表
  //   imageList.value = history.images || []
  //   
  //   // 触发相关选项的更新
  //   handleStageChange(history.stage)
  //   handleSubjectChange(history.subject)
  // }
}

// 处理教学阶段变化
const handleStageChange = (value) => {
  formData.value.subject = ''
  formData.value.objective = ''
  subjects.value = subjectsMap[value] || []
}

// 处理科目变化
const handleSubjectChange = (value) => {
  // 不再重置教学目标，因为现在是自由输入
}

// 预览图片
const handlePreview = async (image) => {
  if (!image || !image.url) {
    ElMessage.warning('图片URL无效，无法预览');
    return;
  }
  
  // 直接使用图片URL，不发送API请求
  previewUrl.value = image.url;
  previewTitle.value = image.title || '教学图片';
  previewVisible.value = true;
}

// 下载图片
const handleDownload = async (image) => {
  try {
    // 直接从URL下载图片
    const response = await fetch(image.url);
    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `${image.title || 'image'}.jpg`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success('下载成功');
  } catch (error) {
    console.error('下载图片失败:', error);
    ElMessage.error('下载失败');
  }
}

// 处理图片加载错误
const handleImageError = (image) => {
  console.error('图片加载失败:', image.url);
  image.loadFailed = true;
}

// 重新加载图片
const reloadImage = (image) => {
  // 检查URL是否存在
  if (!image || !image.url) {
    // URL不存在时使用备用图片
    if (image) {
      image.url = `https://picsum.photos/800/600?random=${Math.random()}`;
      image.loadFailed = false;
      ElMessage.warning('使用备用图片替代');
    }
    return;
  }
  
  // 对于OSS链接，可能需要重新获取有效URL
  if (image.url.includes('oss-cn-wulanchabu') || image.url.includes('aliyuncs.com')) {
    // 尝试从后端重新获取图片URL
    generateTeachingImage({
      id: image.id,
      refreshUrl: true
    }).then(response => {
      if (response.data && response.data.url) {
        image.url = response.data.url;
        image.loadFailed = false;
        ElMessage.success('已重新获取图片链接');
      }
    }).catch(error => {
      console.error('重新获取图片链接失败:', error);
      // 如果重新获取失败，使用备用图片
      image.url = `https://picsum.photos/800/600?random=${Math.random()}`;
      image.loadFailed = false;
      ElMessage.warning('使用备用图片替代');
    });
  } else {
    // 对于非OSS链接，刷新URL参数重新加载
    image.url = image.url.includes('?') ? 
      `${image.url.split('?')[0]}?t=${Date.now()}` : 
      `${image.url}?t=${Date.now()}`;
    image.loadFailed = false;
  }
}

// 检查表单是否填写完整
const checkForm = () => {
  if (!formData.value.stage) {
    ElMessage.warning('请选择教学阶段')
    return false
  }
  if (!formData.value.subject) {
    ElMessage.warning('请选择教学科目')
    return false
  }
  if (!formData.value.objective) {
    ElMessage.warning('请填写教学目标')
    return false
  }
  if (!formData.value.style) {
    ElMessage.warning('请填写图片风格')
    return false
  }
  if (!formData.value.size) {
    ElMessage.warning('请选择图片尺寸')
    return false
  }
  return true
}

// 生成图片
const generateImages = async () => {
  if (!checkForm()) return
  
  isGenerating.value = true
  try {
    // 获取科目标签
    const subjectItem = subjects.value.find(item => item.value === formData.value.subject);
    const subjectLabel = subjectItem ? subjectItem.label : formData.value.subject;
    
    // 获取阶段标签
    const stageItem = stages.value.find(item => item.value === formData.value.stage);
    const stageLabel = stageItem ? stageItem.label : formData.value.stage;
    
    // 获取图片尺寸
    let imageSize;
    switch(formData.value.size) {
      case 'small':
        imageSize = '768*768';
        break;
      case 'medium':
        imageSize = '1024*1024';
        break;
      case 'large':
        imageSize = '1280*768';
        break;
      default:
        imageSize = '1024*1024';
    }
    
    console.log('发送通义万象图片生成请求:', {
      subject: subjectLabel,
      grade: stageLabel,
      topic: subjectLabel,
      description: `教学目标：${formData.value.objective}\n图片风格：${formData.value.style}`,
      imageCount: formData.value.imageCount,
      size: imageSize
    });
    
    try {
      // 调用后端API，由后端代理调用通义万象API
      const response = await generateTeachingImage({
        subject: subjectLabel,
        grade: stageLabel,
        topic: subjectLabel,
        description: `教学目标：${formData.value.objective}\n图片风格：${formData.value.style}`,
        imageCount: formData.value.imageCount,
        size: imageSize
      });
      
      console.log('通义万象图片生成成功:', response);
      
      if (response.data) {
        // 处理单个图片对象的情况
        let imageData = response.data;
        
        // 确保图片数据包含必要的字段
        if (!imageData.url) {
          console.warn('API返回的图片数据缺少URL字段，使用备用URL');
          imageData.url = `https://picsum.photos/800/600?random=${Math.random()}`;
        }
        
        // 添加其他可能缺失的字段
        imageData = {
          id: imageData.id || Date.now(),
          title: imageData.title || `${subjectLabel}教学图片`,
          description: imageData.description || formData.value.objective,
          format: imageData.format || 'jpg',
          size: imageData.size || formData.value.size,
          ...imageData
        };
        
        imageList.value = [imageData];
        ElMessage.success('图片生成成功');
      } else {
        throw new Error('API响应缺少data字段');
      }
    } catch (apiError) {
      console.error('通义万象API请求失败，使用模拟数据:', apiError);
      
      // 使用模拟数据作为临时方案
      imageList.value = [];
      
      // 根据请求的图片数量生成模拟图片
      for (let i = 0; i < formData.value.imageCount; i++) {
        imageList.value.push({
          id: Date.now() + i,
          title: `${subjectLabel}教学图片 ${i+1}`,
          description: formData.value.objective,
          url: `https://picsum.photos/800/600?random=${Math.random()}`,
          size: formData.value.size,
          format: 'jpg'
        });
      }
      
      ElMessage.warning('使用模拟数据替代真实图片');
    }
    
  } catch (error) {
    console.error('生成图片过程中发生错误:', error);
    ElMessage.error('生成图片失败，请稍后重试');
  } finally {
    isGenerating.value = false;
  }
}

// 处理预览图片加载错误
const handlePreviewError = () => {
  console.error('预览图片加载失败:', previewUrl.value);
  ElMessage.error('图片预览加载失败');
}

// 重新加载预览图片
const reloadPreview = () => {
  // 检查URL是否存在
  if (!previewUrl.value) {
    // 使用随机备用图片
    previewUrl.value = `https://picsum.photos/1200/800?random=${Math.random()}`;
    ElMessage.warning('使用备用图片替代');
    return;
  }
  
  // 对于OSS链接，可能需要重新获取有效URL
  if (previewUrl.value.includes('oss-cn-wulanchabu') || previewUrl.value.includes('aliyuncs.com')) {
    // 使用随机备用图片
    previewUrl.value = `https://picsum.photos/1200/800?random=${Math.random()}`;
    ElMessage.warning('使用备用图片替代');
  } else {
    // 对于非OSS链接，刷新URL参数重新加载
    previewUrl.value = previewUrl.value.includes('?') ? 
      `${previewUrl.value.split('?')[0]}?t=${Date.now()}` : 
      `${previewUrl.value}?t=${Date.now()}`;
  }
}

onMounted(() => {
  // 设置默认值
  if (formData.value.stage) {
    handleStageChange(formData.value.stage)
  }
})
</script>

<style scoped>
.image-container {
  display: flex;
  max-width: 1600px;
  margin: 0 auto;
  padding: 20px;
  gap: 30px;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.selection-panel {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.action-panel {
  text-align: center;
  margin: 20px 0;
}

.image-list {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.image-item .el-image {
  width: 100%;
  height: 200px;
}

.image-info {
  padding: 15px;
}

.image-info h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.image-info p {
  margin: 0 0 10px 0;
  color: #666;
}

.image-meta {
  display: flex;
  gap: 20px;
  color: #999;
  font-size: 14px;
}

.image-wrapper {
  position: relative;
  overflow: hidden;
  border-radius: 4px;
}

.image-actions {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-wrapper:hover .image-actions {
  opacity: 1;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
  background-color: #f5f7fa;
  padding: 20px;
  box-sizing: border-box;
}

.image-error i {
  font-size: 32px;
  margin-bottom: 10px;
  color: #909399;
}

.image-error p {
  margin-bottom: 10px;
  color: #606266;
}

.image-preview-dialog :deep(.el-dialog__body) {
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background: #f5f7fa;
}

.preview-content {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-content .el-image {
  max-width: 100%;
  max-height: 600px;
}

.preview-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
  background-color: #f5f7fa;
  padding: 20px;
  box-sizing: border-box;
}

.preview-error i {
  font-size: 32px;
  margin-bottom: 10px;
  color: #909399;
}

.preview-error p {
  margin-bottom: 10px;
  color: #606266;
}
</style> 